<script lang="ts">
import { ApiError } from '@peng_kai/kit/request';
import { InputPassword } from '~comp/input';
import { flzxsqc } from '~/utils';

export function validatePassword(v: string) {
  if (!/^.{8,20}$/.test(v))
    return formResult($t('3pmPAa711sGgTmbUNu4Y'));
  if (/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(v))
    return formResult($t('aTqY6CSclH4yaPkBgWVkj'));
  if (!/^(?=.*[a-z])(?=.*[A-Z])|(?=.*[a-z])(?=.*\d)|(?=.*[A-Z])(?=.*\d).+$/.test(v))
    return formResult($t('vvN3hyzbeI7Mo7voWpaf'));
  return formResult();
}

export function toAgentSignIn() {
  window.open('https://ag.g9.game/', '_blank');
}
</script>

<script lang="ts" setup>
const form = useAntdForm({
  name: {
    value: '',
    rules: [{ required: true, message: 'Please enter the name' }],
  },
  email: {
    value: '',
    rules: [{ required: true, type: 'email', message: 'Please enter the email.' }],
  },
  telegram_username: {
    value: '',
    rules: [{ required: true, message: 'Please enter the telegram username' }],
  },
  company_name: {
    value: '',
    rules: [{ required: true, message: 'Please enter the company name' }],
  },
  traffic_sources: {
    value: '',
    rules: [{ required: true, message: 'Please enter the traffic sources' }],
  },
  password: {
    value: '',
    rules: [{
      validator(_, v) {
        if (!v)
          return formResult('Please enter the password.');
        return validatePassword(v);
      },
    }],
  },
  password_confirm: {
    value: '',
    rules: [{
      validator(_, v) {
        if (!v)
          return formResult('Please enter the confirm password.');
        if (v !== form.state.password)
          return formResult('The two password entries are inconsistent');
        return validatePassword(v);
      },
    }],
  },
  is_agreement: {
    value: true,
    rules: [{ validator(_, v) {
      if (!v)
        return formResult($t('ywffgOzz2yce3hBpSw8d'));
      return formResult();
    } }],
  },
});

const agentSignUpMut = useMutation({
  mutationKey: [apis.apiAgentSignup.id],
  mutationFn: apis.apiAgentSignup.setDefaultConfig({ errorMessage: false }),
  onSuccess() {
    antdMessage.success({ content: 'Submitted', duration: 3 });
  },
  onError(e, { requestBody: body }) {
    const isApiError = e instanceof ApiError;

    if (isApiError && e.code === 15024 && body?.email) {
      antdMessage.success({ content: 'We will send the verification code to the email address you provided. Please check your email inbox.', duration: 3 });
      globalPopups.verifyEmail.open({ type: 1, email: body.email });
      return;
    }
    antdMessage.error({ content: e.message, duration: 3 });
  },
});

const getIsLoadingRef = computed(() => agentSignUpMut.isPending.value);

async function submit() {
  const state = await form.$form.validate?.();
  if (state) {
    agentSignUpMut.mutateAsync({
      requestBody: {
        ...form.state,
        password: flzxsqc(form.state.password),
        password_confirm: flzxsqc(form.state.password_confirm),
      },
    });
  }
}

const nameInputDom = ref();
const appStore = useAppStore();

defineExpose({ focus: () => nameInputDom.value?.focus() });
</script>

<template>
  <div id="registration" class="mb-4 overflow-hidden pt-20">
    <div class="container">
      <div class="flex gap-4 lt-mobilel:(block)">
        <div class="registration-form">
          <div class="mb-4">
            <h2 class="mb-4 text-4.5 font-600 -tracking-.02em">
              Sign Up
            </h2>
            <AForm v-bind="form.props" class="ant-cover__Form-compact" :disabled="false" @finish="submit()">
              <TAntdTheme component="Input" theme="light">
                <AFormItem v-bind="form.itemProps.name">
                  <AInput ref="nameInputDom" v-model:value="form.state.name" placeholder="Name" allowClear>
                    <template #prefix>
                      <i class="i-ri:user-3-fill mr-1 text-1.2em text-sys-text-body" />
                    </template>
                  </AInput>
                </AFormItem>

                <AFormItem v-bind="form.itemProps.email">
                  <AInput v-model:value="form.state.email" placeholder="Email" allowClear>
                    <template #prefix>
                      <i class="i-local:email mr-1 text-1.2em text-sys-text-body" />
                    </template>
                  </AInput>
                </AFormItem>

                <AFormItem v-bind="form.itemProps.telegram_username">
                  <AInput v-model:value="form.state.telegram_username" placeholder="Enter your telegram username" allowClear>
                    <template #prefix>
                      <i class="i-ri:telegram-2-fill mr-1 text-1.2em text-sys-text-body" />
                    </template>
                  </AInput>
                </AFormItem>

                <AFormItem v-bind="form.itemProps.company_name">
                  <AInput v-model:value="form.state.company_name" placeholder="Company name" allowClear>
                    <template #prefix>
                      <i class="i-local:sign--company mr-1 text-1.2em text-sys-text-body" />
                    </template>
                  </AInput>
                </AFormItem>

                <AFormItem v-bind="form.itemProps.traffic_sources">
                  <AInput v-model:value="form.state.traffic_sources" placeholder="Traffic sources" allowClear>
                    <template #prefix>
                      <i class="i-local:sign--source mr-1 text-1.2em text-sys-text-body" />
                    </template>
                  </AInput>
                </AFormItem>

                <AFormItem v-bind="form.itemProps.password">
                  <InputPassword v-model:value="form.state.password" placeholder="Enter password" />
                </AFormItem>

                <AFormItem v-bind="form.itemProps.password_confirm">
                  <InputPassword v-model:value="form.state.password_confirm" placeholder="Confirm password" />
                </AFormItem>

                <AFormItem class="!mb-4 !mt-1">
                  <AButton
                    class="ant-cover__Button-3d-primary w-full"
                    type="primary"
                    :loading="getIsLoadingRef"
                    :disabled="getIsLoadingRef"
                    @click="submit()"
                  >
                    Create account
                  </AButton>
                </AFormItem>

                <AFormItem class="!mt-0" v-bind="form.itemProps.is_agreement">
                  <ACheckbox v-model:checked="form.state.is_agreement">
                    <p class="text-3 text-sys-text-body">
                      By accessing you confirm that you are agree to the
                    </p>
                  </ACheckbox>
                  <RouterLink :to="{ name: RN.HELP_PRIVACY_POLICY }">
                    <span class="text-3 text-brand-500" rel="noreferrer">Terms of Service</span>
                  </RouterLink>
                </AFormItem>
              </TAntdTheme>
            </AForm>
          </div>
          <div>
            <p class="mb-7.5 text-3 lt-mobilel:(mb-4)">
              Do you have an account? <span class="cursor-pointer text-brand-500" @click="toAgentSignIn"> Login </span>
            </p>
            <img class="h-full w-full" src="../imgs/intro-banner-desc-mb.png">
          </div>
        </div>
        <div class="registration-contacts">
          <img class="registration-intro" src="../imgs/raccoon.png">
          <div class="relative z-2 rounded-4 bg-sys-layer-a p-6">
            <p class="mb-5.5 text-4.5 text-sys-text-body lt-mobilel:(text-3.5)">
              Contact us if you have any questions. We'd be happy to hear from you!
            </p>

            <div class="contact-info">
              <a :href="appStore.handshake?.telegram_customer_id" target="_blank">
                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18" fill="none">
                  <path d="M14.0811 4.97241L7.25149 11.2831V15.2767L9.69875 13.2144L13.2416 15.7268C13.3285 15.8188 13.4333 15.8922 13.5496 15.9423C13.6659 15.9924 13.7911 16.0182 13.9177 16.0182C14.0443 16.0182 14.1696 15.9924 14.2859 15.9423C14.4021 15.8922 14.5069 15.8188 14.5939 15.7268C14.915 14.6963 17.7666 2.62622 17.1695 2.26785C16.5253 1.88095 0.812498 8.00001 0.812498 8.00001C0.768917 8.10856 0.747724 8.2248 0.750193 8.34175C0.752662 8.45869 0.778742 8.57393 0.826866 8.68055C0.87499 8.78716 0.944166 8.88295 1.03024 8.96216C1.11631 9.04137 1.2175 9.10236 1.32774 9.14148C2.44569 9.6469 3.61051 10.0415 4.80548 10.3195C5.38521 10.3815 14.0792 4.97427 14.0792 4.97427" fill="#848A9D" />
                  <path d="M1.32651 9.14036C2.16355 9.54461 4.27784 10.5664 4.80425 10.3184C6.44112 9.54213 14.078 4.97314 14.078 4.97314" fill="#848A9D" />

                </svg><span>{{ appStore.handshake?.telegram_customer_id }}</span></a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.registration-form {
  box-shadow: 8px 8px 50px #00000026;
  --uno: 'bg-sys-layer-a z-1 w-50% relative p-6 rounded-3 self-end';
  --uno: 'lt-mobilel:(w-full p-4)';
  .input {
    width: 100%;
  }
}
.registration-contacts {
  --uno: 'w-50% relative self-end lt-mobilel:(mt-78 w-full) ';
  .registration-intro {
    --uno: 'w-110% absolute max-w-none -top-200% left-50% -translate-50% lt-tabletl:(-top-180% w-120) lt-mobilel:(-top-120% w-88)';
  }
}
.contact-info {
  a {
    --uno: 'font-600 decoration-none whitespace-nowrap flex items-center';
  }
  span {
    --uno: 'ml-2.5 text-4 font-400';
  }
}
</style>
